<?php
/**
 * 简单的API测试脚本
 * 用于测试OA系统的核心API接口
 */

require_once 'vendor/autoload.php';

use think\facade\Db;

class ApiTester
{
    private $baseUrl = 'http://localhost:8000';
    private $username = 'liuhui';
    private $password = 'zhilv2023';
    private $token = null;
    private $userInfo = null;

    public function __construct()
    {
        echo "开始API测试...\n";
    }

    /**
     * 发送HTTP请求
     */
    private function request($method, $uri, $data = [], $headers = [])
    {
        $url = $this->baseUrl . $uri;
        
        // 添加认证头
        if ($this->token) {
            $headers['Authorization'] = 'Bearer ' . $this->token;
        }
        
        // 添加内容类型头
        if (!isset($headers['Content-Type']) && in_array($method, ['POST', 'PUT', 'PATCH'])) {
            $headers['Content-Type'] = 'application/json';
        }

        $curl = curl_init();
        
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $this->buildHeaders($headers),
        ]);
        
        if (!empty($data) && in_array($method, ['POST', 'PUT', 'PATCH'])) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        
        curl_close($curl);
        
        if ($error) {
            throw new Exception("cURL Error: " . $error);
        }
        
        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("JSON decode error: " . json_last_error_msg());
        }
        
        return [
            'status_code' => $httpCode,
            'data' => $result
        ];
    }

    /**
     * 构建HTTP头
     */
    private function buildHeaders($headers)
    {
        $result = [];
        foreach ($headers as $key => $value) {
            $result[] = $key . ': ' . $value;
        }
        return $result;
    }

    /**
     * 测试用户登录
     */
    public function testLogin()
    {
        echo "测试用户登录...\n";
        
        try {
            $response = $this->request('POST', '/api/auth/login', [
                'username' => $this->username,
                'password' => $this->password
            ]);
            
            if ($response['status_code'] === 200 && $response['data']['code'] === 0) {
                $this->token = $response['data']['data']['token'];
                $this->userInfo = $response['data']['data']['userInfo'];
                
                echo "✓ 登录成功\n";
                echo "  Token: " . substr($this->token, 0, 20) . "...\n";
                echo "  用户ID: " . $this->userInfo['id'] . "\n";
                echo "  用户名: " . $this->userInfo['username'] . "\n";
                return true;
            } else {
                echo "✗ 登录失败: " . $response['data']['msg'] . "\n";
                return false;
            }
        } catch (Exception $e) {
            echo "✗ 登录异常: " . $e->getMessage() . "\n";
            return false;
        }
    }

    /**
     * 测试登录失败情况
     */
    public function testLoginFailures()
    {
        echo "测试登录失败情况...\n";
        
        // 测试空用户名和密码
        try {
            $response = $this->request('POST', '/api/auth/login', [
                'username' => '',
                'password' => ''
            ]);
            
            if ($response['status_code'] === 200 && $response['data']['code'] === 1) {
                echo "✓ 空用户名密码登录被正确拒绝: " . $response['data']['msg'] . "\n";
            } else {
                echo "✗ 空用户名密码登录处理异常\n";
            }
        } catch (Exception $e) {
            echo "✗ 测试空用户名密码登录时发生异常: " . $e->getMessage() . "\n";
        }
        
        // 测试不存在的用户
        try {
            $response = $this->request('POST', '/api/auth/login', [
                'username' => 'nonexistentuser',
                'password' => 'wrongpassword'
            ]);
            
            if ($response['status_code'] === 200 && $response['data']['code'] === 1) {
                echo "✓ 不存在用户登录被正确拒绝: " . $response['data']['msg'] . "\n";
            } else {
                echo "✗ 不存在用户登录处理异常\n";
            }
        } catch (Exception $e) {
            echo "✗ 测试不存在用户登录时发生异常: " . $e->getMessage() . "\n";
        }
        
        // 测试错误密码
        try {
            $response = $this->request('POST', '/api/auth/login', [
                'username' => $this->username,
                'password' => 'wrongpassword'
            ]);
            
            if ($response['status_code'] === 200 && $response['data']['code'] === 1) {
                echo "✓ 错误密码登录被正确拒绝: " . $response['data']['msg'] . "\n";
            } else {
                echo "✗ 错误密码登录处理异常\n";
            }
        } catch (Exception $e) {
            echo "✗ 测试错误密码登录时发生异常: " . $e->getMessage() . "\n";
        }
    }

    /**
     * 测试Check接口
     */
    public function testCheckApi()
    {
        if (!$this->token) {
            echo "✗ 无法测试Check接口，需要先登录\n";
            return false;
        }
        
        echo "测试Check接口...\n";
        
        try {
            // 测试获取审批列表
            $response = $this->request('GET', '/api/check/index');
            
            if ($response['status_code'] === 200) {
                echo "✓ Check接口访问成功\n";
                if (isset($response['data']['code']) && $response['data']['code'] === 0) {
                    echo "  返回数据条数: " . (isset($response['data']['data']['list']) ? count($response['data']['data']['list']) : '未知') . "\n";
                }
            } else {
                echo "✗ Check接口访问失败，状态码: " . $response['status_code'] . "\n";
            }
        } catch (Exception $e) {
            echo "✗ 测试Check接口时发生异常: " . $e->getMessage() . "\n";
        }
    }

    /**
     * 测试Demo接口
     */
    public function testDemoApi()
    {
        if (!$this->token) {
            echo "✗ 无法测试Demo接口，需要先登录\n";
            return false;
        }
        
        echo "测试Demo接口...\n";
        
        try {
            $response = $this->request('GET', '/api/demo/index');
            
            if ($response['status_code'] === 200) {
                echo "✓ Demo接口访问成功\n";
            } else {
                echo "✗ Demo接口访问失败，状态码: " . $response['status_code'] . "\n";
            }
        } catch (Exception $e) {
            echo "✗ 测试Demo接口时发生异常: " . $e->getMessage() . "\n";
        }
    }

    /**
     * 测试Index接口
     */
    public function testIndexApi()
    {
        if (!$this->token) {
            echo "✗ 无法测试Index接口，需要先登录\n";
            return false;
        }
        
        echo "测试Index接口...\n";
        
        try {
            $response = $this->request('GET', '/api/index/index');
            
            if ($response['status_code'] === 200) {
                echo "✓ Index接口访问成功\n";
            } else {
                echo "✗ Index接口访问失败，状态码: " . $response['status_code'] . "\n";
            }
        } catch (Exception $e) {
            echo "✗ 测试Index接口时发生异常: " . $e->getMessage() . "\n";
        }
    }

    /**
     * 运行所有测试
     */
    public function run()
    {
        $this->testLoginFailures();
        $loginSuccess = $this->testLogin();
        
        if ($loginSuccess) {
            $this->testCheckApi();
            $this->testDemoApi();
            $this->testIndexApi();
            echo "\n所有测试完成！\n";
            return true;
        } else {
            echo "\n测试失败！\n";
            return false;
        }
    }
}

// 运行测试
$tester = new ApiTester();
exit($tester->run() ? 0 : 1);